home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2167 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.6 KB  |  65 lines

  1. Path: unix.sri.com!usenet
  2. From: mklenk@updike.sri.com (Mark Klenk)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Returning a variable from system() functi
  5. Date: 19 Jan 1996 16:01:57 GMT
  6. Organization: SRI International
  7. Message-ID: <4dof9l$fk9@unix.sri.com>
  8. References: <295336694wnr@iiga.demon.co.uk>
  9. Reply-To: mklenk@updike.sri.com
  10. NNTP-Posting-Host: 204.75.161.40
  11.  
  12. Pete Ryan wrote:
  13. >
  14. >    I`ve just been experimenting with C on UNIX and have come across a 
  15. >problem!.  There is a UNIX command called `find / -name gwire -print` 
  16. >which scans the UNIX drive for files/directories containing `gwire`.  
  17. >Anyway what I want to do is the following...
  18. >
  19. >#include <stdio.h>
  20. >#include <stdlib.h>
  21.  
  22. Add
  23. #include <unistd.h>
  24.  
  25.  
  26. >void main()
  27. >{
  28. >    char    tmp[];
  29. >    
  30. >    chdir("/usr2/willesden");    
  31. >    
  32. >    */ offending code below ;( */
  33. >    tmp = system("find . -name gwire");
  34.  
  35. Instead, use popen() - see the man page for popen/pclose.
  36.     FILE * fp;
  37.     char   line[1024];
  38.     fp = popen("find . -name gwire", "r");
  39.     if (NULL == fp) {
  40.         fprintf(stderr, "Unable to execute command.\n");
  41.         exit(EXIT_FAILURE);
  42.     }
  43.     while (NULL != fgets(line, sizeof(line), fp)) {
  44.         printf("%s", line);
  45.     }
  46.     pclose(fp);
  47.  
  48. >Therefore if I run `find . -name gwire -print` it returns all the 
  49. >directories containing `gwire`.  However the code above does not 
  50. >work!!. Is it because `= system` returns an integer and not strings???
  51.  
  52.     Yes, that's part of your answer.  system() returns the status
  53.     of the command, not its output.  The output usually goes to
  54.     stdout and/or stderr, of which you can only capture stdout
  55.     with popen().
  56.  
  57.  
  58.  
  59. ---
  60.  
  61. mklenk@coronacorp.com       (Mark Klenk)
  62.  
  63.  
  64.  
  65.